package com.runchinaup.sifitbledome.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.runchinaup.sifitbledome.R;
import com.runchinaup.sifitbledome.ble.DataInterface;
import com.runchinaup.sifitbledome.ble.conn.ConnResult;
import com.runchinaup.sifitbledome.domain.SendData;
import com.runchinaup.sifitbledome.domain.SyncHeartRateData;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity implements DataInterface.DataCallback {

    final static int RECODE = 000;
    static final int REQUEST_BT = 111;
    private TextView centerTitle;
    private TextView electricity;
    private ListView listView;
    private MainAdapter mainAdapter;
    //连接成功没有的标示
    private boolean isConn = false;

    //    static BleHelper bleHelper = BleHelper.getBleHelper();
    private static DataInterface dataInterface = DataInterface.getDataInterface();
    private SendData sendData = new SendData();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.ui_main);
        openBlue();
        initView();
        //注册蓝牙连接的回调
//        bleHelper.registerBleListener(this);
        dataInterface.resgistData(this);
    }

    //是否打开蓝牙
    private void openBlue() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_BT);
        }
    }

    //初始化
    private void initView() {

        centerTitle = findViewById(R.id.centerText);
        centerTitle.setText("bleDome");

        electricity = findViewById(R.id.electricity);

        listView = findViewById(R.id.listview);

        mainAdapter = new MainAdapter(this, listData);

        listView.setAdapter(mainAdapter);
    }

    //进入连接界面
    public void jumpToScan(View view) {

        startActivityForResult(new Intent(this, ScanActivity.class), RECODE);

    }

    //连接界面的回调还有打开蓝牙的回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_BT) {
            if (resultCode != RESULT_OK) {
                Toast.makeText(this, "请打开蓝牙", Toast.LENGTH_SHORT).show();
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        openBlue();
                    }
                }, 500);
            }
        }

        //扫描连接完成后的回调
        if (requestCode == RECODE) {
//            isConn = true;
            if (data != null) {
                isConn = data.getBooleanExtra("isConn", false);
            }
        }
    }

    //接收连接状态
    @Override
    public void onConnectResult(final ConnResult connResult) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (connResult == ConnResult.CONN_DIS) {
                    Toast.makeText(MainActivity.this, "断开连接", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    //回调的电量
    @Override
    public void getEletricity(final byte[] data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isConn) {
//                    StringBuilder builder = new StringBuilder();
//                    for (byte b : data) {
//                        builder.append(String.format("%02x", (b & 0xff)));
//                    }
//                    Log.e("debug_data", builder.toString());

                    if (data[3] == 0x04) {  //电池电量的数据  04  01
                        if (data[4] == 0x01) {
                            electricity.setText(String.format("%02d", (data[7] & 0xff)));
                        }
                    }
                }
            }
        });
    }

    //获取的同步心率的数据
    ArrayList<StringBuilder> list = new ArrayList<StringBuilder>();
    ArrayList<SyncHeartRateData> listData = new ArrayList<>();

    @Override
    public void getHeartRate(byte[] data) {

        if (data[3] == 0x0a) {
            if (data[4] == 0x03) {

                list.clear();
            }
        }
        if (data[3] == 0x04) {  //电池电量的数据  04  01

        } else {
            StringBuilder stringBuilder = new StringBuilder();
            for (byte b : data) {
                stringBuilder.append(String.format("%02x", (b & 0xff)));
            }
            list.add(stringBuilder);
        }

        Log.e("debug_sync_rate", list.size() + "");

        StringBuilder sb = new StringBuilder();
        for (StringBuilder s : list) {
            sb.append(s);
        }
        Log.e("debug_sb", sb.toString());
        int len = sb.length();
        final byte[] byteData = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            byteData[i / 2] = (byte) Integer.parseInt(sb.substring(i, i + 2), 16);
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                SyncHeartRateData syncHeartRateData;
                for (int i = 7; i < byteData.length / 7; i += 7) {
                    syncHeartRateData = new SyncHeartRateData();
                    syncHeartRateData.setYear(String.format("%02d", (byteData[i] & 0xff)));
                    syncHeartRateData.setMonth(String.format("%02d", (byteData[i + 1] & 0xff)));
                    syncHeartRateData.setDay(String.format("%02d", (byteData[i + 2] & 0xff)));
                    syncHeartRateData.setHour(String.format("%02d", (byteData[i + 3] & 0xff)));
                    syncHeartRateData.setMinute(String.format("%02d", (byteData[i + 4] & 0xff)));
                    syncHeartRateData.setSecond(String.format("%02d", (byteData[i + 5] & 0xff)));
                    syncHeartRateData.setRate(String.format("%03d", (byteData[i + 6] & 0xff)));
                    listData.add(syncHeartRateData);
                    mainAdapter.notifyDataSetChanged();
                }
            }
        });
    }


    //同步时间的按钮
    public void syncTime(View view) {

        Time time = new Time();
        time.setToNow();
        int year = time.year % 2000;
        int month = time.month + 1;
        int day = time.monthDay;
        int hour = time.hour;
        int minute = time.minute;
        int second = time.second;

        byte[] vaule = new byte[]{
                (byte) year, (byte) month, (byte) day, (byte) hour, (byte) minute, (byte) second
        };
        byte[] length = new byte[]{(byte) vaule.length, 0x00};
        sendData.setCommend((byte) 2);
        sendData.setKey((byte) 1);
        sendData.setLength(length);
        sendData.setValue(vaule);
        dataInterface.sendToBle(sendData);
    }

    //进入测试心率的界面
    public void heartRate(View view) {
        if (!isConn) {
            Toast.makeText(this, "请先连接蓝牙", Toast.LENGTH_SHORT).show();
        } else {
            startActivity(new Intent(this, HeartRateActivity.class));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        dataInterface.resgistData(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dataInterface.disconn();
    }

    public void syncHeartRate(View view) {
        if (isConn) {
            //同步心率的数据
            sendData.setCommend((byte) 0x0a);
            sendData.setKey((byte) 3);
            sendData.setValue(new byte[]{18, 03, 16});
            sendData.setLength(new byte[]{(byte) sendData.getValue().length, 0x00});
            dataInterface.sendToBle(sendData);
        } else {
            Toast.makeText(this, "请先连接蓝牙", Toast.LENGTH_SHORT).show();
        }
    }
}
